/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package filespliter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Administrator
 */
public class FileSpliter {
 
    private FileSpliterArgs args;
    private List blockIndexMapList;
    private long fileLen;
    private RandomAccessFile raf;
    private MappedByteBuffer buffer;
    private FileChannel channel;
    private File dir;

    public FileSpliter(FileSpliterArgs args) {
        this.blockIndexMapList = new ArrayList<Long[]>();
        this.args = args;
        fileLen = args.file.length();
        String filename=args.file.getName();
        dir = new File(args.dir+File.separator+ filename.substring(0,filename.indexOf(".")) +"_split");
        if (!dir.isDirectory()) {
            dir.mkdirs();
        }
        try {
            raf = new RandomAccessFile(args.file, "r");
        } catch (FileNotFoundException ex) {
            Logger.getLogger(FileSpliter.class.getName()).log(Level.SEVERE, null, ex);
            System.exit(0);
        }
        channel = raf.getChannel();
        if (fileLen <= args.blockSize) {
            blockIndexMapList.add(new long[]{0, fileLen});
        } else {
            int blockCount = (int) Math.ceil((float)fileLen / args.blockSize); 
            long lastBlockSize = fileLen - (blockCount - 1) * args.blockSize;
            long endIndex = 0;
            for (long i = 1; i <= blockCount; i++) {
                long startIndex = args.blockSize * (i - 1);
                endIndex = startIndex + (i == blockCount ? lastBlockSize : args.blockSize);
                long[] index = new long[]{startIndex, endIndex};
                blockIndexMapList.add(index);
            }
            if (args.withLine) {
                long foreEnterIndex = 0;
                for (int i = 0; i < blockIndexMapList.size(); i++) {
                    long[] index2 = (long[]) blockIndexMapList.get(i);
                    index2[1] = getNearestEnterIndex(index2[1]);
                    if (i > 0) {
                        index2[0] = foreEnterIndex + 1;
                    }
                    foreEnterIndex = index2[1];
                }
            }
        }

        for (int i = 0; i < blockIndexMapList.size(); i++) {
            long[] index2 = (long[]) blockIndexMapList.get(i);
//            System.out.print("(" + i + ")" + index2[0]);
//            System.out.println("-->" + index2[1]);
            save(index2[0], index2[1], i + 1);
        }
        System.out.println("(done)");
    }

    private long getNearestEnterIndex(long startIndex) {
        try {
            raf.seek(startIndex);
            if (raf.read() == '\n') {
                return startIndex + 1;
            } else {
                int read = raf.read();
                while (read != -1 && read != '\n') {
                    startIndex++;
                    read = raf.read();
                }
                return ++startIndex;
            }
        } catch (IOException ex) {
            Logger.getLogger(FileSpliter.class.getName()).log(Level.SEVERE, null, ex);
            System.exit(0);
            return -1;
        }
    }

    private void save(long start, long end, long blockIndex) {
        long len = end + 1 - start;
        if (start + len > fileLen) {
            len = fileLen - start;
        }
        long mapBufferSize = 200 * 1024 * 1024;//100M
        String filerawname = args.file.getName();
        String fileNameIndex=String.format("%0"+String.valueOf(blockIndexMapList.size()).length()+"d", blockIndex);
        File outfile = new File(dir.getAbsolutePath() + File.separator + filerawname.substring(0, filerawname.indexOf(".")) + "_" + fileNameIndex + filerawname.substring(filerawname.indexOf(".")));
        try {
            System.out.println("("+blockIndex+")"+outfile.getAbsolutePath());
            outfile.createNewFile();
            FileChannel channel2 = new FileOutputStream(outfile).getChannel();
            if (len <= mapBufferSize) {
                buffer = channel.map(FileChannel.MapMode.READ_ONLY, start, len);
                channel2.write(buffer);
                channel2.force(true);
                channel2.close();
            } else {
                List maplist = new ArrayList<Long[]>();
                int mapCount = (int) Math.ceil((float)len / mapBufferSize);
                long lastMapSize = len - (mapCount - 1) * mapBufferSize;
//                System.out.println(lastMapSize);
                for (long i = 1; i <= mapCount; i++) {
                    if (i == mapCount) {
                        maplist.add(new long[]{start + (i - 1) * mapBufferSize, lastMapSize});
                    } else {
                        maplist.add(new long[]{start + (i - 1) * mapBufferSize, mapBufferSize});
                    }
                }
                for (int i = 0; i < maplist.size(); i++) {
                    long[] index = (long[]) maplist.get(i);
                    buffer = channel.map(FileChannel.MapMode.READ_ONLY, index[0], index[1]);
//                    System.out.println(index[0]);
                    channel2.write(buffer);
                    channel2.force(true);
                }
                channel2.close();
            }
        } catch (IOException ex) {
            Logger.getLogger(FileSpliter.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
